﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using VkClientIM.Logic;
using Vkontakte.Api;
using Vkontakte.Api.Operations;
using WPFMediaKit.DirectShow.Controls;

namespace VkClientIM.Windows
{
	/// <summary>
	/// Interaction logic for VideosWindow.xaml
	/// </summary>
	public partial class VideosWindow : Window
	{
		private Profile _profile;
		private MediaUriElement mediaElement;

		public VideosWindow()
		{
			InitializeComponent();
		}

		protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
		{
			if (mediaElement != null)
			{
				mediaElement.Stop();
				mediaElement.Close();
				mediaElement = null;
			}
			base.OnClosing(e);
		}

		public void AttachProfile(Profile profile)
		{
			_profile = profile;
			this.DataContext = profile;
			VideoGet videoGet = new VideoGet();
			videoGet.UserID = _profile.UserID;
			videoGet.Completed += delegate
			                      	{
			                      		Dispatcher.Invoke(new Action(delegate
			                      		                  	{
																Video[] videos = videoGet.GetResult();
																videoPanel.DataContext = videos;
			                      		                  	}));
			         
			                      	};
			App.Current.ApiClient.ExecuteHighPriorityQuerry(videoGet);
		}

		private void VideoPanelSelectionChanged(object sender, SelectionChangedEventArgs e)
		{
			Video v = e.AddedItems[0] as Video;
			string url = App.Current.ApiClient.GetVideoLocation(string.Format("video{0}_{1}", v.OwnerID, v.VideoID));
			if (mediaElement!=null)
			{
				content.Child = null;
				mediaElement.Stop();
				mediaElement.Close();
				mediaElement.Source = null;
				mediaElement.Close();
				mediaElement = null;
			}
			mediaElement=new MediaUriElement();
			content.Child = mediaElement;
			mediaElement.BeginInit();
			mediaElement.LoadedBehavior = WPFMediaKit.DirectShow.MediaPlayers.MediaState.Manual;
			mediaElement.Source = new Uri(url);
			mediaElement.EndInit();
			mediaElement.Play();
		}

		private ManualResetEventSlim _event = new ManualResetEventSlim(true);

		private void mediaElement_MediaOpened(object sender, RoutedEventArgs e)
		{

		}

		private void mediaElement_MediaClosed(object sender, RoutedEventArgs e)
		{
			_event.Set();
		}

		private void mediaElement_MediaFailed(object sender, WPFMediaKit.DirectShow.MediaPlayers.MediaFailedEventArgs e)
		{

		}
	}
}
